<template>
	<view class="">
		<ncDusease titleName="修改病害" compoType="modify" ref="updateRef"
			:subTitleName="updataObj.lineSiteSectionName || ''" :lineSiteSectionType="updataObj.lineSiteSectionType || ''"  @addSubmit="addSubmit" v-model="updataObj.mileage"></ncDusease>
	</view>
</template>

<script>
	import ncDusease from '../../common/ncDusease.vue'
	import mixins from '@/utils/mixins.js'
	import { BS, BSM } from '@/session/index.js'
	import { diseaseOrderSave, diseaseOrderGetDetails, getDetailsList, getLastFillingRecord } from "@/api/engineeringMaintenance/engineeringMaintenance.js"
	import { uploadFile } from '@/utils/request'
	import { getToken } from '@/utils/auth.js'
	import { getImageBase64, getImageByDocId } from "@/utils/imageOperation.js"
	import { doGet, doSave, doDelete } from "@/utils/offline/sqlite/index.js";
	//巡检的所有接口
	import * as XUNJIAN from '@/api/engineeringMaintenance/engineeringMaintenance.js'
	import { getPicture, deleteImg, doc_deleteAttachs } from '@/api/doc.js'
	import { urlTobase64, uploadImageFromBase64} from '@/utils/imageOperation.js'
	export default {
		name: 'changeDisease',
		components: {
			ncDusease
		},
		mixins: [mixins],
		data() {
			return {
				updataObj: {},
				mileage: '',
				requestStatus: false,
				isRequest:false
			}
		},
		onLoad(params) {
			if (params && params.id) {
				//请求详情接口
				doGet(XUNJIAN.diseaseOrderGetDetails, {
						id: params.id
					})
					.then(async res => {
						console.log(res, '新增tab修改页的详情');
						if (!res.success) return
						this.updataObj = res.result
						this.$set(this.updataObj, 'videoFileList', [])
						console.log(this.updataObj.mileage,'000000');
						this.$set(this.updataObj, 'diseaseGrade', res.result.diseaseGradeName)
						if (res.result.docId) {
							const attachRes = await doGet(getPicture, {
								docId: res.result.docId
							})
							if (attachRes.success && attachRes.result) {
								let imgResult = attachRes.result.map(it => ({
									id: it.id,
									url: it.fileName ?
										this.$config.IMG_FILE_URL + it.fileName :
										it.url
								}))
								this.$set(this.updataObj, 'fileListImg', imgResult)
								this.updataObj.sourceImgs = JSON.parse(JSON.stringify(imgResult))
							}
						}
						
						if (res.result.videoDocId) {
							const attachRes = await doGet(getPicture, {
								docId: res.result.videoDocId
							})
							if (attachRes.success && attachRes.result) {
								let videoResult = attachRes.result.map(it => ({
									id: it.id,
									url: it.fileName ?
										this.$config.VIDEO_URL + it.fileName :
										it.url
								}))
								this.$set(this.updataObj, 'videoFileList', videoResult)
								this.updataObj.sourceVideos = JSON.parse(JSON.stringify(videoResult))
							}
						}
						this.$set(this.updataObj, 'updateIds', [])
						this.$set(this.updataObj, 'updateVideoIds', [])
						this.updataObj.removeFileSet = new Set()
						this.$refs.updateRef.changeBefore = this.updataObj
						console.log(this.updataObj, '===103行')
					})
			}
		},
		async beforeDestroy() {
			if(!this.isRequest) {
				console.error('销毁钩子函数',this.updataObj)
				// 新加图片后没有点击操作按钮直接退出 需要删除新加的id
				let needDelIds = [], needDelIds2 = []
				if(this.updataObj.updateIds.length) {
					let ids = this.updataObj.sourceImgs.map(i => i.id)
					needDelIds = this.getDifference(ids, this.updataObj.updateIds)
				}
				// 删除视频
				if(this.updataObj.updateVideoIds.length) {
					let ids = this.updataObj.sourceVideos.map(i => i.id)
					needDelIds2 = this.getDifference(ids, this.updataObj.updateVideoIds)
				}
				
				 let allIds = [].concat(needDelIds, needDelIds2)
				if(allIds.length) {
					await doc_deleteAttachs(allIds)
				}
				// 找出删除的数据 原数据和现在的数组对比,并上传
				let result = this.getArrDifSameValue(this.updataObj.fileListImg, this.updataObj.sourceImgs || [])
				console.error(result)
				if(result.length) {
					let base64List = []
					let dataList = []
					for(let it of result) {
						const base64_img = await urlTobase64(it.url)
						base64List.push(base64_img.split(",")[1])
					}
					// 水印数据
					let formData = {}
					//区间/站点
					formData.name = this.updataObj.lineSiteSectionName
					//里程
					const distance = this.getContent2(this.updataObj)
					//环号
					const startRing = this.updataObj.startNumber || ''
					const endRing = this.updataObj.endNumber || ''
					const others = this.updataObj.others || ''
					const timeClock = this.updataObj.clockwisePosition || ''
					formData.ring =
						`${distance}${distance && startRing ? ',' : ''}${startRing}${startRing && endRing ? '~' : '' }${endRing}${(distance && others)||(endRing && others) ? ',' : ''}${others}${(distance && timeClock)  ||  (startRing && endRing && timeClock) || (others&&timeClock)  ? ',' : ''}${timeClock}`
					//现状
					formData.status = this.updataObj.diseaseStatus || ''
					formData.dateTime = this.getDate2(new Date)
					let response = await uploadImageFromBase64({
						dataList:[formData.name, formData.ring, formData.status, formData.dateTime],
						docId:this.updataObj.docId,
						base64List
					})
					console.error(response, '结果')
				}
				
				
				//找出删除的视频并且重新上传
				// let result2 = this.getArrDifSameValue(this.updataObj.videoFileList, this.updataObj.sourceVideos || [])
				// console.log(result2, '视频文件')
				// if(result2.length) {
				// 	for(let item of result2) {
				// 		uni.downloadFile({
				// 			url: item.url,
				// 			success: async (res) => {
				// 				if (res.statusCode === 200) {
				// 					console.error(res,'下载成功');
				// 					// #ifdef MP-WEIXIN
				// 					const uploadResq = {
				// 						url: "rest/doc/uploadDoc",
				// 						formData:{ docId:this.updataObj.videoDocId, },
				// 						name: 'attach',
				// 						filePath: res.tempFilePath,
				// 						isOffline: true
				// 					}
				// 					// #endif
									
				// 					// #ifdef APP-PLUS || H5
				// 					const uploadResq = {
				// 						url: "rest/doc/uploadDoc",
				// 						formData:{ docId:this.updataObj.videoDocId, },
				// 						files: [{
				// 							name: "attach",
				// 							uri: res.tempFilePath
				// 						}],
				// 						isOffline: true
				// 					}
				// 					// #endif
				// 					let data = await doSave(uploadFile, uploadResq)
				// 					console.error(data, '165行上传视频')
				// 				}
				// 			}
				// 		});
				// 	}
				// }
			}
			
		},
		methods: {
			//新增按钮事件
			async addSubmit(obj) {
				console.error(obj)
				// return
				this.$set(obj, 'orderType', 'add')
				this.$set(obj, 'createDate', new Date().getTime())
				this.$set(obj, 'projectId', uni.getStorageSync('isOwner'))
				//获取存储到本地的线路区间站点然后作为入参传递 删除mileage字段
				const localLine = JSON.parse(uni.getStorageSync('lineData'))
				const {result} =  await doGet(getLastFillingRecord, localLine)
				this.$delete(localLine,'mileage')
				this.$set(obj, 'inspectUser', result.inspectUser)
				let testObj = Object.assign(obj, localLine)
				if(testObj && testObj.videoFileList && testObj.videoFileList.length > 0){
					const taskArr = testObj.videoFileList.filter(it => it.uploadStatus)
					if(taskArr.length > 0) {
						uni.showToast({
							title:'视频上传中,请稍等',
							icon:'none',
							mask:true
						})
						return
					}
				}
				const hasRing = !!(testObj.startNumber && testObj.endNumber)
				const hasMile = !!(testObj.startMileageFront && testObj.startMileageAfter && testObj.endMileageFront && testObj
					.endMileageAfter)
				const hasOther = !!(testObj.others)
				const hasStationLocation = !!(testObj.stationLocation)
				if (!hasRing && !hasMile && !hasOther && !hasStationLocation) {
					if (testObj.lineSiteSectionType == 'qj') {
						uni.showToast({
							title: '里程、环号、其他中必须填写一个!',
							icon: 'none',
						})
					} else if (testObj.lineSiteSectionType == 'cz') {
						uni.showToast({
							title: '车站位置和其他中必须填写一个!',
							icon: 'none',
						})
					} else {
						uni.showToast({
							title: '位置为必填项!',
							icon: 'none',
						})
					}
					return
				}
				if (!hasRing && (testObj.startNumber || testObj.endNumber)) {
						return uni.showToast({
							title:'请检查数据格式',
							icon:'none'
						})
				}
				if (!hasMile && (testObj.startMileageFront || testObj.startMileageAfter || testObj.endMileageFront || testObj.endMileageAfter)) {
						return uni.showToast({
							title:'请检查数据格式',
							icon:'none'
						})
				}
				if(this.requestStatus) return
				this.requestStatus = true
				// 删除视频记录的视频id
				let arr = [...testObj.removeFileSet] || []
				if(arr.length) {
					await doc_deleteAttachs(arr)
				}
				doSave(XUNJIAN.diseaseOrderSave, { ...testObj })
					.then(res => {
						this.isRequest = true
						console.log(res, '新增编辑时返回的结果');
						if (res.success) {
							uni.showToast({
								title: '成功',
								icon: 'none',
								mask: true,
							})
							setTimeout(() => {
								uni.navigateBack()
								this.requestStatus = false
							}, 1600)
						}else {
							this.requestStatus = false
						}
					})
			},

		}
	}
</script>

<style lang="scss" scoped>

</style>
